package com.sali.Tree;

/**
 * 给定一个二叉树，统计该二叉树数值相同的子树个数。
 * <p>
 * 同值子树是指该子树的所有节点都拥有相同的数值。
 */
public class LeetCode_250 {


    int res = 0;

    public int countUnivalSubtrees(TreeNode root) {
        getRes(root);
        return res;
    }

    private boolean getRes(TreeNode curNode) {
        if ( curNode == null ) {
            return true;
        }

        boolean leftJudge = getRes(curNode.left);
        boolean rightJudge = getRes(curNode.right);

        if ( leftJudge && rightJudge ) {
            boolean left = curNode.left == null ? true : curNode.val == curNode.left.val;
            boolean right = curNode.right == null ? true : curNode.val == curNode.right.val;
            if ( left && right ) {
                res++;
            }
            return left && right;
        }

        return false;
    }

}
